
import json, os, sys, random, _thread

def rand_str(k=16, cc='0123456789ABCDEF'):
	cc = list(cc)
	return ''.join(random.sample(cc,k))

def _app_cpp(request_, response_, route_args_):
	with open('web/index.html') as fp:
		content = fp.read()
	app = route_args_['app'].strip()
	content = content.replace("var app='main'", f"var app='{app}'")
	from . import cpp_tools
	try:
		data = request_.params_.get('data', None)
		if data is not None:
			data = json.loads(data)
	except:
		pass
	if data is None:
		data = {}
	if 'app' not in data:
		data['app'] = app
	if 'session' not in data:
		data['session'] = rand_str()
	app = f'{app}.cpp' if os.path.isfile(f'cpp/{app}.cpp') else f'{app}.c'
	cp_err, stdout, stderr = cpp_tools.run_source(app, data)
	if stderr!='':
		data['stderr'] = stderr
	if cp_err=='':
		content = content.replace("<body></body>", f"<body onload=init()>{stdout}</body>")
		content = content.replace("data = {}", "data = " + json.dumps(data, ensure_ascii=False))
	else:
		content = content.replace("<body></body>", f"<body><font color=RED><pre>{cp_err}</pre></font></body>")	
	return response_.write_response_OK_(content_type_='text/html', content_=content, charset_='UTF-8')

_lock = _thread.allocate_lock()
def _app(request_, response_, route_args_):
	app = route_args_['app'].strip()
	if app=='':
		route_args_['app'], app = 'main', 'main'
	if os.path.isfile(f'cpp/{app}.cpp') or os.path.isfile(f'cpp/{app}.c'):
		with _lock:
			return _app_cpp(request_, response_, route_args_)
	return response_.write_response_error_(400, f'不存在 cpp/{app}.cpp 或 cpp/{app}.c')

http_ = None
def _start_server(port_, max_threads_):
	from .lib.http_ import Http_
	global http_
	assert http_ is None
	http_ = Http_(ip_='0.0.0.0', port_=port_, web_path_='web', max_threads_=max_threads_)
	http_.add_route_('/{app}', _app, 'GET')
	http_.add_route_('/{app}', _app, 'POST')
	http_.start_()

port = int(sys.argv[1]) if len(sys.argv)>=2 else 80

print(f'网页服务器端口: {port}')
_start_server(port, 100)
print('网页服务器已关闭')
